#!/usr/bin/env python
"""
##############################################################################
用法：./cleanpyc rootdir [-f(findonly)]

删除目录树中所有.pyc字节码文件：如果给出命令行参数则将其视为根目录，否则将当前工作目录作为根
目录。
##############################################################################
"""

import find
import sys
import os

FINDONLY = False
ROOTDIR = os.getcwd


def cleanpyc(rootdir=ROOTDIR, findonly=FINDONLY):
    print('rootdir ->', rootdir, 'findonly ->', findonly)
    found = removed = 0
    for pyc in find.find('*.pyc', rootdir):
        found += 1
        print(pyc)
        if not findonly:
            try:
                os.remove(pyc)
            except Exception:
                print(
                    '*' * 4, '删除失败：', pyc,
                    sys.exc_info()[0], sys.exc_info()[1]
                )
            else:
                removed += 1
    print('发现了', found, '个pyc文件，删除了', removed, '个。')


def command(rootdir=ROOTDIR, findonly=FINDONLY):
    rootdir = sys.argv[1] if len(sys.argv) > 1 else rootdir
    findonly = '-f' in sys.argv
    cleanpyc(rootdir, findonly)


if __name__ == '__main__':
    command()
